package group_1.MultiSnake;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.MotionEvent;

public class GameActivity extends BaseGameActivity implements IOnSceneTouchListener, SnakeConstants{
	// ===========================================================
    // Constants
    // ===========================================================

    private static final int CAMERA_WIDTH = 720; 	// The width of the gamefield
    private static final int CAMERA_HEIGHT = 480; 	// The height of the gamefield
    
    private static final int FPS = 50;				// frames per second
    
    // ===========================================================
    // Fields
    // ===========================================================

    private float touchDownX;						// stores the x-position of last screentouch
    private float touchDownY;						// stores the y-position of last screentouch
    private boolean moving = false;					// no new screentouches are registered when set to true
    
    private SnakeGameEngine gameEngine = null;		// runs the gameloop and handle gamelogic
    
    private Camera mCamera;							// represents the gamefield
    private BitmapTextureAtlas bitmapTextureAtlas;	// stores all images used to draw the snakes
    private BitmapTextureAtlas itemTextureAtlas;	// stores all images used to draw the items
    private TextureRegion bodyTextureRegion;		// stores a single image used to draw vertical and horizontal bodyparts
    private TextureRegion headTextureRegion;		// stores a single image used to draw the head of the snake
    private TextureRegion bodyTurnTextureRegion;	// stores a single image used to draw the turn of the snake
    private TextureRegion bulletTextureRegion;		// stores a single image used to draw a bullet
    
    /**
     * Called when loading the engine
     * Sets the type of gameengine to use
     */
    @Override
    public Engine onLoadEngine() {
        this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
        gameEngine = new SnakeGameEngine(new EngineOptions(
        		true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera), FPS, this);
        return gameEngine;
    }

    /**
     * Called when loading all resources needed during gameplay
     */
    @Override
    public void onLoadResources() {
    	this.bitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
        this.bodyTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, this, "snake_body.png", 0, 0);
        this.bodyTextureRegion.setHeight(BODY_THICKNESS);
        this.bodyTextureRegion.setWidth(BODY_THICKNESS);
        this.bodyTurnTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, this, "snake_body_turn.png", BODY_THICKNESS, 0);
        this.bodyTurnTextureRegion.setHeight(BODY_THICKNESS);
        this.bodyTurnTextureRegion.setWidth(BODY_THICKNESS);
        this.headTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, this, "snake_head.png", 0, BODY_THICKNESS);
        this.headTextureRegion.setHeight(HEAD_WIDTH);
        this.headTextureRegion.setWidth(HEAD_LENGTH);
        this.mEngine.getTextureManager().loadTexture(this.bitmapTextureAtlas);
        
        
        this.itemTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
        this.bulletTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.itemTextureAtlas, this, "bullet.png", 0, 0);
        this.bulletTextureRegion.setHeight(BULLET_HEIGHT);
        this.bulletTextureRegion.setWidth(BULLET_WIDTH);
        this.mEngine.getTextureManager().loadTextures(itemTextureAtlas);
        
    }

    /**
     * Called when loading the scene (the gamefield).
     * 
     */
    @Override
    public Scene onLoadScene() {
    		// Register an update handler for the gameengine
            this.mEngine.registerUpdateHandler(new FPSLogger());
            
            final Scene scene = new Scene();
            scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
            
            scene.setOnSceneTouchListener(this);
            return scene;
    }

    /**
     * Called when all initializing to make the game activity run is done.
     * 
     */
    @Override
    public void onLoadComplete() {    	
    	Bundle extras = getIntent().getExtras();
        String gameInfo = extras.getString(getString(R.string.game_key));
//        ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.waitPlayers_text), false, true);
        ProgressDialog dialog = null;
    	gameEngine.newGame(bodyTextureRegion, bodyTurnTextureRegion, headTextureRegion, bulletTextureRegion, gameInfo, dialog);
    }
    
    /**
     * When the application is exit or moved to background all threads
     * used are released.
     */
    @Override
    public void onPause() {
    	super.onPause();
    	if(gameEngine.isRunning()) {
	    	gameEngine.shutDown();
    	}
    }
    
    /**
     * Handle user touchevents.
     * Save position of touch and send the data to the gameengine for it to
     * determine what the action should be
     */
	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pTouchEvent) {
		MotionEvent me = pTouchEvent.getMotionEvent();
		float newX, newY;
		
		if(pTouchEvent.getAction() == MotionEvent.ACTION_DOWN && !moving) {
			moving = true;
            touchDownX = me.getX();
            touchDownY = me.getY();
        }else if(pTouchEvent.getAction() == MotionEvent.ACTION_UP && moving ||
        		pTouchEvent.getAction() == MotionEvent.ACTION_POINTER_UP) {
            newX = me.getX();
            newY = me.getY();
            moving = false;
            gameEngine.posInputOperation((int)touchDownX, (int)touchDownY, (int)newX, (int)newY);
        }
        return true;
	}
}